import React, {useEffect} from "react";
import {Breadcrumb, Button, Cascader, CascaderProps, Col, DatePicker, Form, Input, message, Row, Select} from "antd";
import type {Result} from "@/types/result";
import candidateApi from "@/api/candidateApi.ts";
import {Candidate} from "@/types/resp/candidate";
import { AreaOption } from "@/types/areaOption";
import areas from "@/locales/area.json";
import { useNavigate } from "react-router-dom";


const CandidateAddOfJobSeeker: React.FC = () => {

  const navigate = useNavigate();
  const [form] = Form.useForm<Candidate>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    username: [
      { required: true, message: '请输入用户名' }
    ],
    name: [
      { required: true, message: '请输入姓名' }
    ],
    password: [
      { required: true, message: '请输入密码' }
    ],
    gender: [
      { required: true, message: '请输入性别' }
    ],
    birthDate: [
      { required: true, message: '请输入出生日期' }
    ],
    contactPhone: [
      { required: true, message: '请输入联系电话' }
    ],
    email: [
      { required: true, message: '请输入邮箱' }
    ],
  };

  let candidateForm: Partial<Candidate> = {}

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '编辑基本信息'}
  ]

  const provinceCityAreaOptions: AreaOption[] = areas.provinces

  useEffect(() => {
    initCandidateFormById(1)
  }, []);

  const initCandidateFormById = async (id: number) => {
    const resp: Result<Candidate> = await candidateApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      candidateForm = resp.data
      const provinceCityArea2 = []
      if (candidateForm.province) {
        provinceCityArea2.push(candidateForm.province)
      }
      if (candidateForm.city) {
        provinceCityArea2.push(candidateForm.city)
      }
      if (candidateForm.area) {
        provinceCityArea2.push(candidateForm.area)
      }
      form.setFieldsValue({...candidateForm, provinceCityArea: provinceCityArea2});
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let candidate2Save:Candidate = form.getFieldsValue()
      candidate2Save = Object.assign(candidateForm, candidate2Save)
      const resp: Result<void> = await candidateApi.save(candidate2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    form.resetFields();
  };

  const onAreaChange: CascaderProps<AreaOption>['onChange'] = (value) => {
    if (value && value.length > 0 && typeof value[0] === 'string') {
      candidateForm.province = value[0]
    }
    if (value && value.length > 1 && typeof value[1] === 'string') {
      candidateForm.city = value[1]
    }
    if (value && value.length > 2 && typeof value[2] === 'string') {
      candidateForm.area = value[2]
    }
  };

  return (
    <div>
      {messageContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} name="candidateForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="username" label="用户名" rules={rules.username}>
              <Input maxLength={64} placeholder="请输入用户名"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="name" label="姓名" rules={rules.name}>
              <Input maxLength={64} placeholder="请输入姓名"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="password" label="密码" rules={rules.password}>
              <Input maxLength={255} placeholder="请输入密码"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="gender" label="性别" rules={rules.gender}>
              <Select placeholder="请选择性别" options={[
                { value: 1, label: <span>男</span> },
                { value: 2, label: <span>女</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="birthDate" label="出生日期" rules={rules.birthDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="contactPhone" label="联系电话" rules={rules.contactPhone}>
              <Input maxLength={64} placeholder="请输入联系电话"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="email" label="邮箱" rules={rules.email}>
              <Input maxLength={64} placeholder="请输入邮箱"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="provinceCityArea" label="省/市/区">
              <Cascader options={provinceCityAreaOptions} fieldNames={{ label: "name", value: "code" }} onChange={onAreaChange} placeholder="请选择省/市/区" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="address" label="家庭地址">
              <Input maxLength={255} placeholder="请输入家庭地址"/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div className="custom-footer">
        <Button type="primary" onClick={onSave}>保存</Button>
        <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      </div>
    </div>
  )
}

export default CandidateAddOfJobSeeker;
